The if statement it can be extended with an optional else block to provide an alternative code path when the condition is false:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
#include <iostream>
int main() {
int age = 15;
if (age >= 18) {
std::cout << "are an adult." << std::endl;
} else {
std::cout << "are not an adult." << std::endl;
}
return 0;
}
In this case, if the age is less than 18, the message "are not an adult" is displayed.
it can chain multiple conditions using else if to handle more complex decision-making scenarios:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition1 is false and condition2 is true
} else {
// Code to be executed if all previous conditions are false
}
#include <iostream>
int main() {
int score = 85;
if (score >= 90) {
std::cout << "A" << std::endl;
} else if (score >= 80) {
std::cout << "B" << std::endl;
} else if (score >= 70) {
std::cout << "C" << std::endl;
} else {
std::cout << "F" << std::endl;
}
return 0;
}
In this example, the code checks the score and prints a corresponding grade based on the value of score.
The if statement is a fundamental control structure in C++ and is used extensively for making decisions and controlling the flow of program.
question
question2